package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Service.AuthService;
import com.example.chamberlainserver.Service.TokenValidationService;
import com.example.chamberlainserver.Vo.Request.User.LoginVo;
import com.example.chamberlainserver.Vo.Request.User.PhoneLoginVo;
import com.example.chamberlainserver.Vo.Request.User.RegisterVo;
import com.example.chamberlainserver.Vo.Request.User.SmsCodeRequestVo;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.Vo.Response.JwtResponse;
import com.example.chamberlainserver.security.LogoutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private LogoutFilter logoutFilter;
    
    @Autowired
    private TokenValidationService tokenValidationService;

    /**
     * 用户登录
     *
     * @param loginRequest 登录请求
     * @return JWT令牌和用户信息
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<JwtResponse>> login(@RequestBody LoginVo loginRequest) {
        JwtResponse jwtResponse = authService.login(loginRequest);
        return ResponseEntity.ok(ApiResponse.success("登录成功", jwtResponse));
    }

    /**
     * 发送短信验证码
     *
     * @param smsCodeRequest 短信验证码请求
     * @return 发送结果
     */
    @PostMapping("/sendSmsCode")
    public ResponseEntity<ApiResponse<String>> sendSmsCode(@RequestBody SmsCodeRequestVo smsCodeRequest) {
        authService.sendSmsCode(smsCodeRequest);
        return ResponseEntity.ok(ApiResponse.success("发送成功", null));
    }

    /**
     * 手机号登录
     *
     * @param phoneLoginRequest 手机号登录请求
     * @return JWT令牌和用户信息
     */
    @PostMapping("/loginByPhone")
    public ResponseEntity<ApiResponse<JwtResponse>> loginByPhone(@RequestBody PhoneLoginVo phoneLoginRequest) {
        JwtResponse jwtResponse = authService.loginByPhone(phoneLoginRequest);
        System.out.println("手机号登录的" + jwtResponse);
        return ResponseEntity.ok(ApiResponse.success("登录成功", jwtResponse));
    }

    /**
     * 用户注册
     *
     * @param registerRequest 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<String>> register(@RequestBody RegisterVo registerRequest) {
        String result = authService.register(registerRequest);
        return ResponseEntity.ok(ApiResponse.success(result, null));
    }


    /**
     * 用户退出登录
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @return 退出结果
     */
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("=== 开始处理退出登录请求 ====");
        System.out.println("请求路径: " + request.getRequestURI());
        System.out.println("请求方法: " + request.getMethod());
        System.out.println("请求头Authorization: " + request.getHeader("Authorization"));
        System.out.println("请求IP: " + request.getRemoteAddr());
        
        try {
            // 获取并验证token
            String requestTokenHeader = request.getHeader("Authorization");
            String jwtToken = tokenValidationService.extractTokenFromHeader(requestTokenHeader);
            boolean hasValidToken = false;
            
            if (jwtToken != null && tokenValidationService.isTokenNotExpired(jwtToken)) {
                hasValidToken = true;
                System.out.println("token有效且未过期");
            } else if (jwtToken == null) {
                System.out.println("缺少有效的Authorization头");
            } else {
                System.out.println("token已过期");
            }
            
            // 获取当前认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            System.out.println("认证信息：" + authentication);
            
            // 无论认证信息是否为空，都尝试处理登出请求
            if (authentication != null && authentication.isAuthenticated()) {
                System.out.println("认证主体: " + authentication.getPrincipal());
                System.out.println("认证权限: " + authentication.getAuthorities());
                
                // 手动调用LogoutFilter的logout方法
                System.out.println("调用LogoutFilter.logout方法");
                logoutFilter.logout(request, response, authentication);
                
                // 清除SecurityContext中的认证信息
                System.out.println("清除SecurityContext中的认证信息");
                SecurityContextHolder.clearContext();
            } else {
                System.out.println("认证信息为空或未认证，尝试直接处理登出");
                // 即使认证信息为空，也尝试调用LogoutFilter的logout方法
                logoutFilter.logout(request, response, authentication);
            }
            
            // 处理Cookie，无论认证信息是否存在
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                System.out.println("处理Cookie: " + cookies.length + "个");
                for (Cookie cookie : cookies) {
                    System.out.println("Cookie名称: " + cookie.getName());
                    if ("jwt".equals(cookie.getName())) {
                        cookie.setValue("");
                        cookie.setPath("/");
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                        System.out.println("已删除JWT Cookie");
                        break;
                    }
                }
            } else {
                System.out.println("没有Cookie需要处理");
            }
            
            // 添加清除Authorization头的响应头
            response.setHeader("Authorization", "");
            // 设置Clear-Site-Data头部，正确格式包含cache、cookies和storage
            response.setHeader("Clear-Site-Data", "\"cache\", \"cookies\", \"storage\"");
            
            System.out.println("=== 退出登录处理完成 ====");
            return ResponseEntity.ok(ApiResponse.success("退出登录成功", null));
        } catch (Exception e) {
            System.err.println("退出登录处理异常: " + e.getMessage());
            e.printStackTrace();
            // 即使发生异常，也尝试清除认证信息
            SecurityContextHolder.clearContext();
            return ResponseEntity.ok(ApiResponse.error("退出登录失败: " + e.getMessage()));
        }
    }
}
